package com.ld.common.util;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.ld.shieldsb.common.composition.util.SecurityUtil;
import com.ld.shieldsb.common.core.model.PropertiesModel;
import com.ld.shieldsb.common.core.util.DateUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CookieUtil {
    private static int expTime = 30; // 默认30分钟过期

    public static void addCookie(HttpServletResponse response, String key, String value) {
        Cookie cookie = new Cookie(key, value);
        // 设置路径，这个路径即该工程下都可以访问该cookie 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
        cookie.setPath("/");
        cookie.setMaxAge(-1); // 随浏览器关闭而关闭
//        cookie.setDomain(PropertiesModel.CONFIG.getString("cookie.domain"));
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    public static void addCookie(HttpServletResponse response, int expiry, String key, String value) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        cookie.setMaxAge(expiry); // 设置超时时间,单位秒
        response.addCookie(cookie);
    }

    public static void addNormalCookie(HttpServletResponse response, String key, String value) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        cookie.setMaxAge(-1); // 随浏览器关闭而关闭
        response.addCookie(cookie);
    }

    public static void removeNormalCookie(HttpServletResponse response, String key) {
        Cookie cookie = new Cookie(key, null);
        cookie.setPath("/");
        cookie.setMaxAge(0); // 立即删除型
        response.addCookie(cookie);
    }

    public static void removeCookie(HttpServletResponse response, String key) {
        Cookie cookie = new Cookie(key, null);
        cookie.setPath("/");
        cookie.setMaxAge(0); // 立即删除型
//        cookie.setDomain(PropertiesModel.CONFIG.getString("cookie.domain"));
        response.addCookie(cookie);
    }

    public static void clearCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            cookie.setMaxAge(0); // 立即删除型
//            cookie.setDomain(PropertiesModel.CONFIG.getString("cookie.domain"));
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }

    public static String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(key)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static void addToken2Cookie(HttpServletResponse response, String loginname, String password, String userType, String isManage,
            String userId) throws Exception {
        if (useSSO()) {
            String dateUtil = DateUtil.getDateTimeString(DateUtil.addDate(new Date(), expTime, Calendar.MINUTE));
            String s = loginname + "\n" + password + "\n" + userType + "\n" + isManage + "\n" + userId + "\n" + dateUtil;
            String token = SecurityUtil.simpleDecrypt(s);
            addCookie(response, "token", token);
        }
    }

    public static void removeToken4Cookie(HttpServletResponse response) {
        if (useSSO()) {
            removeCookie(response, "token");
        }
    }

    public static String getToken4Cookie(HttpServletRequest request) {
        return getCookie(request, "token");
    }

    public static boolean updToken4Cookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    cookie.setPath("/");
                    cookie.setMaxAge(-1); // 有效期随浏览器关闭而关闭
                    cookie.setDomain(PropertiesModel.CONFIG.getString("cookie.domain"));
                    cookie.setHttpOnly(true);
                    response.addCookie(cookie);
                    String tokenEncry = cookie.getValue();
                    try {
                        String token = SecurityUtil.simpleDecrypt(tokenEncry);
                        String[] tokens = token.split("\n");
                        if (tokens != null) {
                            tokens[5] = DateUtil.getDateTimeString(DateUtil.addDate(new Date(), expTime, Calendar.MINUTE));
                        }
                        token = StringUtils.join(tokens, "\n");
                        tokenEncry = SecurityUtil.simpleEncrypt(token);
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                    cookie.setValue(tokenEncry);
                    response.addCookie(cookie);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 更新用户密码
     * 
     * @Title updToken4CookiePwd
     * @author 吕凯
     * @date 2016年4月27日 下午2:11:38
     * @param request
     * @param response
     * @param pwd
     * @return boolean
     */
    public static boolean updToken4CookiePwd(HttpServletRequest request, HttpServletResponse response, String pwd) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    cookie.setPath("/");
                    cookie.setMaxAge(-1); // 有效期随浏览器关闭而关闭
                    cookie.setDomain(PropertiesModel.CONFIG.getString("cookie.domain"));
                    cookie.setHttpOnly(true);
                    response.addCookie(cookie);
                    String tokenEncry = cookie.getValue();
                    try {
                        String token = SecurityUtil.simpleDecrypt(tokenEncry);
                        String[] tokens = token.split("\n");
                        if (tokens != null) {
                            tokens[1] = pwd;
                        }
                        token = StringUtils.join(tokens, "\n");
                        tokenEncry = SecurityUtil.simpleEncrypt(token);
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                    cookie.setValue(tokenEncry);
                    response.addCookie(cookie);
                    return true;
                }
            }
        }
        return false;
    }

    public static String[] getTokenArrfromCookie(String tokenEncry) throws Exception {
        String token = SecurityUtil.simpleDecrypt(tokenEncry);
        String[] tokens = token.split("\n");
        if (tokens != null) {
            String dateUtilStr;
            try {
                dateUtilStr = tokens[5];
            } catch (Exception e) {
                return null;
            }
            Date dateUtil = DateUtil.str2dateTime(dateUtilStr);
            if (dateUtil == null || new Date().after(dateUtil)) {
                return null;
            }
        }
        return tokens;
    }

    public static void main(String[] args) {
        String tokenEncry = "5e9c569da43a799d5aea672b06bf96ba97ba9343a7e647cc3d706b75bba1f42c48949fdb2a541595a4faf4163e5047d7dd2335576a2d2149";
        String token;
        try {
            token = SecurityUtil.simpleDecrypt(tokenEncry);
            String[] tokens = token.split("\n");
            System.out.println(Arrays.asList(tokens));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean useSSO() {
        boolean flag = false;
        String use = PropertiesModel.CONFIG.getString("cookie.usesso", "false");
        try {
            flag = Boolean.parseBoolean(use);
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        return flag;
    }
}
